package nz.co.listit.TaxiValet;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import android.content.Context;
import android.content.Intent;
import nz.co.listit.TaxiValet.ListItC2dmReceiver;

public class ListItSocketListener extends Thread {
	private ServerSocket _serverSocket;
	private Socket _socket;
	private Context _context;
	private Boolean _keepListening = true;

	@Override
	public void interrupt() {
		if (_serverSocket != null)
			try {
				_serverSocket.close();
				_serverSocket = null;
				_socket = null;
				_keepListening = false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		super.interrupt();
	}

	@Override
	public void destroy() {
		try {
			_socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		super.destroy();
	}

	public static String INTENT_LISTIT_SERVER_PING = ListItC2dmReceiver.INTENT_C2DM_FMT
			+ "PING";

	public ListItSocketListener(StatusActivity statusActivity) {
		_context = statusActivity;

		try {
			_serverSocket = new ServerSocket(53709);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			_socket = _serverSocket.accept();
			
			if (!_keepListening)
				return; // no further work required. Owner is terminating
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		while (_keepListening) {
			try {
				Intent intent = new Intent(INTENT_LISTIT_SERVER_PING);
				
				if (_socket == null)
					break;
				
				String ip = _socket.getInetAddress().getHostAddress();

				// get IP address of list-it
				InetAddress inet = InetAddress.getByName("www.list-it.co.nz");

				if (inet != null) {
					if (ip.equals(inet.getHostAddress()))
						_context.sendBroadcast(intent);
				}
	
				// Send a response information to the client application
	
				/*ObjectOutputStream oos = new ObjectOutputStream(_socket.getOutputStream());
				oos.writeObject("OK");
				oos.close();*/

				_socket = _serverSocket.accept();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
